package com.neo.tiny.demo.sso.util;

import cn.hutool.core.util.StrUtil;
import com.neo.tiny.demo.sso.config.security.model.AdminUserDetails;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @Description: 安全工具类
 * @Author: yqz
 * @CreateDate: 2022/8/7 21:10
 */
@UtilityClass
public class SecurityUtils {

    public static final String AUTHORIZATION_BEARER = "Bearer";
    public static final String TOKEN_HEADER = "Authorization";

    /**
     * 解析token
     *
     * @param request 请求头
     * @return token
     */
    public String obtainHeaderToken(HttpServletRequest request) {
        String header = request.getHeader(TOKEN_HEADER);
        // 避免前端只传入空Bearer
        if (StrUtil.isBlank(header)) {
            return null;
        }
        if (header.length() < 7) {
            return null;
        }
        if (header.startsWith(AUTHORIZATION_BEARER)) {
            String bearer = AUTHORIZATION_BEARER + " ";
            return header.substring(bearer.length());
        }
        return null;
    }

    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public AdminUserDetails getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof AdminUserDetails) {
            return (AdminUserDetails) principal;
        }
        return null;
    }


    /**
     * 获取用户
     */
    public AdminUserDetails getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取当前用户id
     *
     * @return 用户id
     */
    public Long getUserId() {
        return Optional.ofNullable(getUser())
                .map(AdminUserDetails::getUserId)
                .orElse(null);
    }
}
